import React, { useState } from 'react';
import { Form, Input, Button, message } from 'antd';
import { Link } from 'react-router-dom';
import "./login.css";
import axios from '../../api/axios';
import { useNavigate } from 'react-router-dom';

const API_URL = '/login';

const Login = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  const onFinish = async (values) => {
    setLoading(true);
    try {
      const response = await axios.post(API_URL, values);
      message.success('登录成功！');
      console.log(response.data); // 可以在这里处理登录成功的逻辑，比如跳转页面
      navigate('/home'); // 登录成功后跳转到首页或其他页面
    } catch (error) {
      message.error('登录失败，请检查账号和密码！');
      console.error('Login error:', error);
    } finally {
      setLoading(false);
    }
  };

  return (
    <Form
      className="login-container"
      onFinish={onFinish}
    >
      <div className="login_title">系统登录</div>
      <Form.Item
        label="账号"
        name="username"
        rules={[{ required: true, message: '请输入账号' }]}
      >
        <Input placeholder="请输入账号" />
      </Form.Item>
      <Form.Item
        label="密码"
        name="password"
        rules={[{ required: true, message: '请输入密码' }]}
      >
        <Input.Password placeholder="请输入密码" />
        <div className="register-link">
          <Link to="/register">还没有账号？立即注册</Link>
        </div>
      </Form.Item>
      <Form.Item className="login-button">
        <Button type="primary" htmlType="submit" loading={loading}>登录</Button>
      </Form.Item>
    </Form>
  );
};

export default Login;